package com.ktg.mes.wm.controller;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktg.common.core.domain.APIResult;
import com.ktg.common.utils.StringUtils;
import com.ktg.mes.md.domain.MdItem;
import com.ktg.mes.md.domain.MdProductStatisticsBom;
import com.ktg.mes.md.service.IMdItemService;
import com.ktg.mes.md.service.IMdProductStatisticsBomService;
import com.ktg.mes.pro.domain.ProItemNeed;
import com.ktg.mes.pro.service.IProItemNeedService;
import com.ktg.mes.pro.service.IProWorkorderService;
import com.ktg.mes.util.LGQueryWrapper;
import com.ktg.mes.wm.domain.WmMaterialStock;
import com.ktg.mes.wm.service.IWmMaterialStockService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.core.domain.Result;
import com.ktg.mes.wm.domain.WmStockWillOut;
import com.ktg.mes.wm.service.IWmStockWillOutService;
import com.ktg.common.utils.poi.ExcelUtil;

/**
 * 产品出库记录Controller
 *
 * @author byteco
 * @date 2022-12-15
 */
@RestController
@RequestMapping("/wm/wmStockWillOut")
public class WmStockWillOutController extends BaseController
{
    @Autowired
    private IWmStockWillOutService wmStockWillOutService;

    @Autowired
    private IProItemNeedService proItemNeedService;

    @Autowired
    private IMdItemService mdItemService;

    @Autowired
    private IMdProductStatisticsBomService statisticsBomService;

    @Autowired
    private IWmMaterialStockService materialStockService;

    @Autowired
    private IProWorkorderService proWorkorderService;

    /**
     * 查询产品出库记录列表
     */
    @PreAuthorize("@ss.hasPermi('wm:wmStockWillOut:list')")
    @GetMapping("/list")
    public Result<IPage<WmStockWillOut>> list(WmStockWillOut wmStockWillOut,
                                            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                            HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询产品出库记录列表",req,null);
        try {
            Page<WmStockWillOut> page = new Page<WmStockWillOut>(pageNo, pageSize);
            IPage<WmStockWillOut> pageList = wmStockWillOutService.queryPageList(wmStockWillOut,page);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 导出产品出库记录列表
     */
    @PreAuthorize("@ss.hasPermi('wm:wmStockWillOut:export')")
    @Log(title = "产品出库记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WmStockWillOut wmStockWillOut,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("导出产品出库记录列表",req,wmStockWillOut);
        try {
            List<WmStockWillOut> list = wmStockWillOutService.queryList(wmStockWillOut);
            ExcelUtil<WmStockWillOut> util = new ExcelUtil<WmStockWillOut>(WmStockWillOut.class);
            util.exportExcel(response, list, "产品出库记录数据");
            apiLog.ok(null);
        }catch (Exception e){
            apiLog.error(e);
        }
    }

    /**
     * 获取产品出库记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('wm:wmStockWillOut:query')")
    @GetMapping(value = "/{recordId}")
    public Result<WmStockWillOut> getInfo(@PathVariable("recordId") Long recordId,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("获取产品出库记录详细信息",req,null);
        try {
            return apiLog.ok(wmStockWillOutService.getInfo(recordId));
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 新增产品出库记录
     */
    @PreAuthorize("@ss.hasPermi('wm:wmStockWillOut:add')")
    @Log(title = "产品出库记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public Result<String> add(@RequestBody WmStockWillOut wmStockWillOut,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增产品出库记录",req,wmStockWillOut);
        try {

            if (StringUtils.isEmpty(wmStockWillOut.getWillOutItemId())){
                return  apiLog.fail("willOutItemId参数缺失1");
            }

            if (StringUtils.isEmpty(wmStockWillOut.getNeedItemId())){
                return  apiLog.fail("needItemId参数缺失2");
            }

            if (wmStockWillOut.getStockType().equals("wm_material_stock")){
                if (!wmStockWillOut.getStockId().contains(":")){
                    WmMaterialStock wmMaterialStock = materialStockService.getById(Long.valueOf(wmStockWillOut.getStockId()));
                    if (wmMaterialStock == null){
                        return  apiLog.fail("库存不存在信息");
                    }
                    wmStockWillOut.setStockId(wmMaterialStock.getWillStockKey());
                }
            }

            Result result = wmStockWillOutService.isWillOutStatus(Long.valueOf(wmStockWillOut.getNeedItemId()),
                    wmStockWillOut.getLinkId(),
                    wmStockWillOut.getStockType(),
                    wmStockWillOut.getStockId(),
                    wmStockWillOut.getQuantity().floatValue());
            if (result.getCode() == -1){
                return apiLog.fail(result.getMsg());
            }

            WmStockWillOut willOut = new WmStockWillOut();
            willOut.setStockType(wmStockWillOut.getStockType());
            willOut.setStockId(wmStockWillOut.getStockId());
            willOut.setLinkType(wmStockWillOut.getLinkType());
            willOut.setLinkId(wmStockWillOut.getLinkId());
            LGQueryWrapper queryWrapper = new LGQueryWrapper<>(willOut,req.getParameterMap());
            willOut = wmStockWillOutService.getOne(queryWrapper);
            if (willOut != null && willOut.getRecordId() != null){
                willOut.setQuantity(wmStockWillOut.getQuantity());
                willOut.setRemark(wmStockWillOut.getRemark());
                wmStockWillOutService.update(willOut);
            }else {
                wmStockWillOutService.insert(wmStockWillOut);
            }

            return apiLog.ok("添加成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 修改产品出库记录
     */
    @PreAuthorize("@ss.hasPermi('wm:wmStockWillOut:edit')")
    @Log(title = "产品出库记录", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public Result<String> edit(@RequestBody WmStockWillOut wmStockWillOut,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改产品出库记录",req,wmStockWillOut);
        try {
            wmStockWillOutService.update(wmStockWillOut);
            return apiLog.ok("编辑成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 删除产品出库记录
     */
    @PreAuthorize("@ss.hasPermi('wm:wmStockWillOut:remove')")
    @Log(title = "产品出库记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{recordIds}")
    public Result<String> remove(@PathVariable Long[] recordIds,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("删除产品出库记录",req,null);
        try {
            wmStockWillOutService.delete(recordIds);
            return apiLog.ok("删除成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }

    }
}
